#!/bin/bash
# ex: ts=8 sw=4 sts=4 et filetype=sh

source /lib/dracut-lib.sh
# Can't do this with dracut-lib... :cry:
#set -e

UNIT_DIR="${1:-/tmp}"

add_requires() {
    local name="$1"
    shift
    local target="$1"
    shift
    local requires_dir="${UNIT_DIR}/${target}.requires"
    mkdir -p "${requires_dir}"
    ln -sf "../${name}" "${requires_dir}/${name}"
}

# In 4.4+, we only activate if rhcos.root=crypt_rootfs as set on the
# kernel cmdline by image.yaml.  This will allow us to go back
# to matching FCOS and supporting full rootfs reprovisioning.
root="$(getargs rhcos.root)"
if [ "${root}" != "crypt_rootfs" ]; then
    exit 0
fi

add_requires coreos-luks-open.service ignition-diskful.target
add_requires coreos-luks-open.service ignition-diskful-subsequent.target

svc=ignition-ostree-growfs.service
svcd="${UNIT_DIR}/${svc}.d"
mkdir -p "${svcd}"
cat > "${svcd}/rhcos.conf" <<EOF
[Unit]
ConditionKernelCommandLine=!rhcos.root=crypt_rootfs
EOF

# Using Tang/NBDE requires the admin to explicitly configure
# on networking in the initramfs unconditionally (beyond just
# the firstboot).  On the Ignition boot, we just
# unconditionally request networking for now. This will be
# fixed when we move to LUKS-via-Ignition, which knows to
# turn on networking only if Tang is requested.
if getargbool 0 rd.neednet; then
    dropindir="${UNIT_DIR}"/coreos-luks-open.service.d
    mkdir -p "${dropindir}"
    dropin=${dropindir}/luks-generator-neednet.conf
    cat > ${dropin} << EOF
[Unit]
# Support Tang/NBDE: Network bound disk encryption
After=network-online.target
Wants=network-online.target
EOF
fi
